<template>
  <el-form
    :model="localFormData"
    label-width="auto"
    style="max-width: 650px"
    ref="ruleFormRef"
    :rules="rules"
    class=""
  >
    <el-row>
      <el-col :span="24">
        <h6 class="pb-3.5 text-gray-400 text-3.5">基础信息</h6>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="商品名称" prop="name" required>
          <el-input v-model="localFormData.name" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="商品编码" prop="code" class="mr-5">
          <el-input v-model="localFormData.code" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品状态" prop="status">
          <el-select
            v-model="localFormData.status"
            placeholder="请选择商品状态"
            style="width: 130px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="商品分类" prop="category_id" required>
          <el-tree-select
            v-model="localFormData.category_id"
            :data="props.categorys"
            :render-after-expand="false"
            show-checkbox
            style="width: 190px"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品slug" prop="slug">
          <el-input v-model="localFormData.slug" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="商品价格" prop="price" class="mr-5">
          <el-input v-model="localFormData.price" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品库存" prop="stock">
          <el-input v-model="localFormData.stock" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-form-item label="商品sku" prop="sku" class="mr-5">
          <el-button @click="showSpecTypesDialog" :disabled="!localFormData.category_id">
            添加规格</el-button
          >

          <el-button @click="resetSkus" circle title="刷新">
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <!-- 商品选择规格后自动生成的sku列表 -->
    <el-row v-if="skuList.length > 0">
      <el-col :span="24" class="pb-3">
        <div class="flex items-center">
          <h6 class="text-sm">商品规格列表</h6>
          <span class="text-xs text-gray-400 px-2.5"
            >建议尺寸：400x400，大小不超过500KB</span
          >
        </div>
        <el-table :data="skuList" border class="mt-4">
          <el-table-column prop="sku_name" label="规格组合" />
          <el-table-column label="价格">
            <template #default="{ row }">
              <el-input-number v-model="row.price" :min="0" :precision="2" />
            </template>
          </el-table-column>
          <el-table-column label="库存">
            <template #default="{ row }">
              <el-input-number v-model="row.stock" :min="0" />
            </template>
          </el-table-column>
          <el-table-column label="图片" width="130">
            <template #default="{ row }">
              <SkuImageUpload
                :api="uploadFile"
                :allowedExtensions="['.jpg', '.jpeg', '.png', '.gif']"
                :maxSizeMB="0.3"
                :multiple="false"
                :limit="1"
                @success="handleSuccess"
                @error="handleError"
              ></SkuImageUpload>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="商品缩略图" prop="thumbnail">
          <ThumbnailUpload
            :api="uploadFile"
            :allowedExtensions="['.jpg', '.jpeg', '.png', '.gif']"
            :maxSizeMB="0.3"
            :multiple="false"
            :limit="1"
            @success="handleSuccess"
            @error="handleError"
          ></ThumbnailUpload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="商品图片" prop="images">
          <GalleryUpload
            :api="uploadFile"
            :allowedExtensions="['.jpg', '.jpeg', '.png', '.gif']"
            :maxSizeMB="2"
            :multiple="true"
            :limit="15"
            @success="handleSuccess"
            @error="handleError"
          ></GalleryUpload>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="localFormData.description" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <el-dialog v-model="dialogSpecVisible" title="选择规格组合" width="650">
    <el-checkbox-group v-model="selectedSpecTypes">
      <el-checkbox v-for="item in specTypes" :key="item.id" :value="item.id" border>
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button @click="dialogSpecVisible = false">取消</el-button>
      <el-button type="primary" @click="handleGenerateSkus">生成SKU</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted, defineExpose, watchEffect } from "vue";
import * as Api from "@/api/index";
import { FormFactory } from "@/core/forms/form-factory";
import { ProductFormData } from "@/core/forms/product-form";
import type { ProductItem, CategoryItem, SpecItem, SpecValue } from "@/api/types/product";
import ThumbnailUpload from "@/components/upload/ThumbnailUpload.vue";
import GalleryUpload from "@/components/upload/GalleryUpload.vue";
import SkuImageUpload from "@/components/upload/SkuImageUpload.vue";
import { isCompleteURL } from "@/utils/util";
import {
  useSkuGenerator,
  useProductForm,
  useImageUpload,
} from "@/composables/products/index";

const SERVER_URL = import.meta.env.VITE_API_SERVER_URL;
const emit = defineEmits(["success"]);
const props = defineProps<{
  formData: ProductItem;
  categorys: CategoryItem[];
  mode: "create" | "edit";
}>();

// 如果是编辑模式，初始化表单数据
const statusOptions = [
  { label: "上架", value: "draft" },
  { label: "下架", value: "published" },
  { label: "已删除", value: "archived" },
];
const localFormData = ref(FormFactory.create("product") as ProductFormData); // 如果是编辑模式，初始化表单数据
console.log(localFormData);

const specTypes = ref<SpecItem[]>([]);

// 初始化 composables
const { selectedSpecTypes, skuList, generateSkus, resetSkus } = useSkuGenerator(
  specTypes
);
const { ruleFormRef, dialogSpecVisible, rules, fetchProductSkuInfo } = useProductForm();
const { uploadFile } = useImageUpload(SERVER_URL);
// 暴露给父组件的异步提交方法
const submit = async () => {
  if (!ruleFormRef.value) return;

  return ruleFormRef.value
    .validate()
    .then(async (valid: boolean) => {
      if (!valid) return false;

      console.log("提交表单skuList:", skuList.value);
      const submitFormData = {
        ...localFormData.value.toSubmitData(),
        skus: skuList.value.map((sku: any) => ({
          specs: sku.specs.map((spec: any) => ({
            name: spec.spec_name,
            spec_type_id: spec.spec_type_id, // 必须包含 spec_type_id
            value: spec.value,
            spec_value_id: spec.spec_value_id,
          })),
          sku_name: sku.sku_name,
          price: sku.price,
          stock: sku.stock,
          image: sku.image,
        })),
      };

      try {
        console.log("提交表单数据:", submitFormData);
        console.log("提交表单数据:", JSON.stringify(submitFormData));
        // return;
        const response =
          props.mode === "create"
            ? await Api.createProduct(submitFormData)
            : await Api.updateProduct(props.formData.id, submitFormData);
        return true;
      } catch (err) {
        throw err; // 会被外部的catch捕获
      }
    })
    .catch((err: any) => {
      console.error("错误:", err);
      return false;
    });
};

const handleSuccess = (url: string) => {
  console.log("上传成功:", url);
  if (!isCompleteURL(url)) {
    localFormData.value.images.push(SERVER_URL + url);
  } else {
    localFormData.value.images.push(url);
  }
  console.log(localFormData.value);
};
const handleError = (err: any) => {
  console.error("上传失败:", err);
};
const handleSkuImageSuccess = (res: any, sku: any) => {
  sku.image = isCompleteURL(res.url) ? res.url : SERVER_URL + res.url;
};
// 4. 生成SKU时调用
const handleGenerateSkus = () => {
  generateSkus(
    Number(localFormData.value.price) || 0,
    Number(localFormData.value.stock) || 0
  );
  
  dialogSpecVisible.value = false;
};
// --获取对应分类下的规格
const fechtSpecTypesList = async (categoryId: string) => {
  const res = await Api.getSpecTypesList(categoryId, {});
  console.log("规格列表：", res);
  specTypes.value = res.list.map((spec: any) => ({
    id: spec.id, // 确保返回的规格类型包含ID
    name: spec.name,
    values: spec.specValues || [], // 处理可能的空值
  })) as SpecItem[];
};
const showSpecTypesDialog = async () => {
  dialogSpecVisible.value = true;
  console.log("选择规格", localFormData.value.category_id);
  await fechtSpecTypesList(localFormData.value.category_id);
};


// 4. 独立的SKU加载函数
const loadSkus = async (productId: string) => {
  try {
    const skuData = await fetchProductSkuInfo(productId);
    console.log("SKU数据:", skuData);
    if (skuData) {
      skuList.value = skuData.map((sku: any) => ({
        id: sku.id,
        specs: sku.specs.map((spec: any) => ({
          spec_type_id: spec.spec_id || spec.spec_type_id,
          spec_name: spec.spec_name,
          spec_value_id: spec.spec_value_id,
          value: spec.value
        })),
        sku_name: sku.sku_name || sku.specs.map((s: any) => s.value).join(" / "),
        price: Number(sku.price) || 0,
        stock: Number(sku.stock) || 0,
        image: sku.image || null
      }));
    }
  } catch (error) {
    console.error('SKU加载失败:', error);
    skuList.value = []; // 失败时清空列表
  }
}

// 自动响应props变化的智能初始化
watchEffect(() => {
  if (props.mode === "edit" && props.formData) {
    console.log("编辑模式，初始化表单数据", props.formData);
    localFormData.value = FormFactory.createFromExisting(
      "product",
      props.formData
    ) as ProductFormData;
    // 并行获取SKU数据（避免阻塞主线程）
    loadSkus(props.formData.id);
  } else {
    localFormData.value = FormFactory.create("product") as ProductFormData;
      skuList.value = []; // 清空SKU列表
  }
});
defineExpose({ submit });
onMounted(() => {
  fetchProductSkuInfo(props.formData.id);
});
</script>
<style scoped lang="scss">
.avatar-uploader .avatar[data-v-11e0307c] {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* 暗黑模式下的悬停颜色 */
.dark :deep(.el-table__body tr:hover > td) {
  background-color: rgba(255, 255, 255, 0.08) !important;
}
</style>
